/**
 *   Copyright (C) 2012  Development Solutions (DS) Software
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *   The following additional terms will apply to the software provided with
 *   this file.
 *      1. Preserve the original authors’ name.
 *      2. Documenting all contributions and specify the contributor's name,
 *         the date of the contribution and some email to future contact.
 * 
 */
package org.dss.gil.view;

import javax.swing.table.DefaultTableModel;
import org.dss.gil.service.MessagesService;
import org.dss.gil.service.ValidationService;
import org.dss.gil.util.Globals;

/**
 *  
 *  @author  Fernando Gil <lobho.gil@gmail.com>
 *  @since   September 2012
 *  @version 1.0
 */
public class Frequencies extends javax.swing.JFrame {

    private ValidationService validations;
    private MessagesService messages;
    private static Frequencies instance;
    
    public static Frequencies getInstance(){
        if(instance==null){
            instance = new Frequencies();
        }
        return instance;
    }
    
    private Frequencies() {
        initComponents();
        setIconImage(Globals.logoImg);
        setLabels();
        validations = ValidationService.getInstance();
        messages = MessagesService.getInstance();
    }

    public void setLabels(){
        setTitle(Globals.language.getMessage("title.freq"));
        jTabbedPane1.setTitleAt(0, Globals.language.getMessage("title.freq.freq"));
        jLabelFreqIns.setText(Globals.language.getMessage("label.freq.ins"));
        jLabelfi.setText(Globals.language.getMessage("label.freq.fi"));
        jLabelni.setText(Globals.language.getMessage("label.freq.ni"));
        jLabelniAcum.setText(Globals.language.getMessage("label.freq.niA"));
        
        jTabbedPane1.setTitleAt(1, Globals.language.getMessage("title.freq.prob"));
        jLabelProbIns.setText(Globals.language.getMessage("label.prob.ins"));
        
    }
    
    
    String [] freqColumNames = new String[]{"fi","ni","ni+"};
    private void calculateRelativeFrequencies() throws Exception{
        
        if(!jTextFrec.getText().trim().isEmpty()){
            DefaultTableModel model = new DefaultTableModel(freqColumNames, 0);
            jTableFreq.setModel(model);
        
            String freq[] = jTextFrec.getText().split(",");
            double total=0;
            for(String f : freq){
                if(validations.isDouble(f)&&Double.parseDouble(f)>0){
                    total+= Double.parseDouble(f);
                }else{
                    messages.showWarningMessage(this, Globals.language.getMessage("message.freq.incorrect"), null);
                    return;
                }
            }
            
            double niAcum =0;
            for(String f : freq){
                String [] newRow = new String[3];
                //double percentage = (Double.parseDouble(f)*100) /total;
                double ni = (Double.parseDouble(f)) /total;
                niAcum+= ni;
                
                newRow[0]=f;
                //newRow[1]=percentage+"";
                newRow[1]=Globals.decimalFormat.format(ni)+"";
                newRow[2]=Globals.decimalFormat.format(niAcum)+"";
                model.addRow(newRow);
            }
            
        }
    }
    
    private void calculateNestedProb() throws Exception{
        String probabilidades = jTextProbab.getText();
        if(!probabilidades.trim().isEmpty()){
            String prob[]=probabilidades.split(",");
            probabilidades="";
            double total = 0;
            boolean sendMessage = false;
            
            
            //Get Total
            for(String p:prob){
                if(validations.isDouble(p)){
                    double num = Double.parseDouble(p);
                    if( (total+num)>100 ){
                        sendMessage = true;
                        num = 100-total;
                    }
                    if(num>0){
                        total+= num;
                        probabilidades += num+",";
                    }else{
                        sendMessage = true;
                    }
                }else{
                    sendMessage = true;
                }
            }
            
            /*Autocomplete the data when the total is less than 100*/
            if(total<100){
                sendMessage = true;
                if(!probabilidades.endsWith(",")){
                    probabilidades+=",";
                }
                probabilidades += (100-total);
                total = 100;
            }
            jTextProbab.setText(probabilidades);
            
            //Calculate
            prob=probabilidades.split(",");
            String resultado="";
            for(int i=0;i<prob.length-1;i++){
                if(validations.isDouble(prob[i])){
                    String value = Globals.decimalFormat.format( (Double.parseDouble(prob[i])) / total );
                    resultado+= "TRANSFER     "+value.substring(value.indexOf(".")) + "\n";
                    total = total-(Double.parseDouble(prob[i])) ;
                }
            }
            jAreaProbas.setText(resultado);
            if(sendMessage){
                messages.showWarningMessage(this, Globals.language.getMessage("message.prob.review"), null);
            }
        }
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanelFreq = new javax.swing.JPanel();
        jTextFrec = new javax.swing.JTextField();
        jLabelFreqIns = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableFreq = new javax.swing.JTable();
        jButton5 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabelfi = new javax.swing.JLabel();
        jLabelni = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabelniAcum = new javax.swing.JLabel();
        jPanelProb = new javax.swing.JPanel();
        jLabelProbIns = new javax.swing.JLabel();
        jTextProbab = new javax.swing.JTextField();
        jScrollPane10 = new javax.swing.JScrollPane();
        jAreaProbas = new javax.swing.JTextArea();
        jButton6 = new javax.swing.JButton();

        setTitle("Simulation Tools");
        setResizable(false);

        jTextFrec.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFrecFocusGained(evt);
            }
        });

        jLabelFreqIns.setText("Ingresa las frecuencias absolutas separadas por comas.");

        jTableFreq.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "fi", "ni", "ni +"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTableFreq);

        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/dss/gil/view/img/calc_x24.png"))); // NOI18N
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jLabel1.setText("fi = ");

        jLabel2.setText("ni = ");

        jLabelfi.setText("frecuencia absoluta");

        jLabelni.setText("frecuencia relativa");

        jLabel5.setText("ni+ = ");

        jLabelniAcum.setText("frecuencia relativa acumulada");

        org.jdesktop.layout.GroupLayout jPanelFreqLayout = new org.jdesktop.layout.GroupLayout(jPanelFreq);
        jPanelFreq.setLayout(jPanelFreqLayout);
        jPanelFreqLayout.setHorizontalGroup(
            jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelFreqLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanelFreqLayout.createSequentialGroup()
                        .add(jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabelFreqIns)
                            .add(jTextFrec, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 458, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jPanelFreqLayout.createSequentialGroup()
                                .add(jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jPanelFreqLayout.createSequentialGroup()
                                        .add(jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(jLabel1)
                                            .add(jLabel2))
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                            .add(jLabelni, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .add(jLabelfi, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                    .add(jPanelFreqLayout.createSequentialGroup()
                                        .add(jLabel5)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(jLabelniAcum, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 196, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 66, Short.MAX_VALUE)
                                .add(jButton5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 148, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap(30, Short.MAX_VALUE))
                    .add(jPanelFreqLayout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(34, Short.MAX_VALUE))))
        );
        jPanelFreqLayout.setVerticalGroup(
            jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelFreqLayout.createSequentialGroup()
                .add(22, 22, 22)
                .add(jLabelFreqIns)
                .add(18, 18, 18)
                .add(jTextFrec, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 31, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanelFreqLayout.createSequentialGroup()
                        .add(jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel1)
                            .add(jLabelfi))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel2)
                            .add(jLabelni, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jPanelFreqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel5)
                            .add(jLabelniAcum, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(jButton5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 62, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                .add(20, 20, 20))
        );

        jTabbedPane1.addTab("frecuencias relativas", jPanelFreq);

        jLabelProbIns.setText("Ingresar probabilidades que sumen 100, separadas por coma.");

        jTextProbab.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextProbabFocusGained(evt);
            }
        });

        jAreaProbas.setColumns(20);
        jAreaProbas.setRows(5);
        jScrollPane10.setViewportView(jAreaProbas);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/dss/gil/view/img/calc_x24.png"))); // NOI18N
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanelProbLayout = new org.jdesktop.layout.GroupLayout(jPanelProb);
        jPanelProb.setLayout(jPanelProbLayout);
        jPanelProbLayout.setHorizontalGroup(
            jPanelProbLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelProbLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanelProbLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane10)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jTextProbab)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabelProbIns, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE)
                    .add(jButton6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(29, Short.MAX_VALUE))
        );
        jPanelProbLayout.setVerticalGroup(
            jPanelProbLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelProbLayout.createSequentialGroup()
                .addContainerGap()
                .add(jLabelProbIns)
                .add(18, 18, 18)
                .add(jTextProbab, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton6)
                .add(18, 18, 18)
                .add(jScrollPane10, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("probabilidades anidadas", jPanelProb);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 529, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 441, Short.MAX_VALUE)
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
    try{
        calculateRelativeFrequencies();
    }catch(Exception ex){
    }
}//GEN-LAST:event_jButton5ActionPerformed

private void jTextFrecFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFrecFocusGained
    jTextFrec.selectAll();
}//GEN-LAST:event_jTextFrecFocusGained

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
    try{
        calculateNestedProb();
    }catch(Exception ex){}
}//GEN-LAST:event_jButton6ActionPerformed

private void jTextProbabFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextProbabFocusGained
    jTextProbab.selectAll();
}//GEN-LAST:event_jTextProbabFocusGained

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea jAreaProbas;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabelFreqIns;
    private javax.swing.JLabel jLabelProbIns;
    private javax.swing.JLabel jLabelfi;
    private javax.swing.JLabel jLabelni;
    private javax.swing.JLabel jLabelniAcum;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanelFreq;
    private javax.swing.JPanel jPanelProb;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane10;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTableFreq;
    private javax.swing.JTextField jTextFrec;
    private javax.swing.JTextField jTextProbab;
    // End of variables declaration//GEN-END:variables

}
